package com.analyse.stock.strategy;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.analyse.stock.annotation.StrategyType;
import com.analyse.stock.config.MailConfig;
import com.analyse.stock.enums.StrategyEnum;
import com.analyse.stock.form.MailInfoForm;
import com.analyse.stock.form.PickStockQueryForm;
import com.analyse.stock.model.FundTopBoardStockModel;
import com.analyse.stock.model.StockKlineDailyModel;
import com.analyse.stock.service.IFundTopBoardStock;
import com.analyse.stock.service.IStockInfo;
import com.analyse.stock.service.impl.StockKlineDailyService;
import com.analyse.stock.utils.MailUtil;
import com.analyse.stock.utils.StockAnalyzer;
import com.analyse.stock.vo.PickStockVO;
import com.analyse.stock.vo.StrategyAnalyseResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
@StrategyType(strategy = StrategyEnum.PICK_STOCK)
public class PickStockIStrategy implements IStrategy {

    @Resource
    private IStockInfo stockInfo;

    @Autowired
    private StockKlineDailyService stockKlineDailyService;

    @Autowired
    private IFundTopBoardStock fundTopBoardStock;

    @Resource
    private MailConfig mailConfig;

    @Override
    public StrategyAnalyseResultVO run(String paramJson) {
        if (StringUtils.isBlank(paramJson)) {
            return null;
        }
        PickStockQueryForm queryForm = JSONObject.parseObject(paramJson, PickStockQueryForm.class);
        PickStockQueryForm.trans(queryForm);
        List<PickStockVO> pickList = stockInfo.pickStock(queryForm);
        if (CollUtil.isEmpty(pickList)) {
            return null;
        }
        List<FundTopBoardStockModel> fundList = Lists.newArrayList();
        if(Objects.isNull(queryForm.getSma())){
            for(PickStockVO stockVO : pickList){
                fundList.add(FundTopBoardStockModel.transModel(stockVO));
                log.info("## 符合条件的股票：{}--{},最新价：{},涨跌幅：{}%, 所属行业板块：{}",
                        stockVO.getStockName(), stockVO.getStockCode(),stockVO.getPrice(),
                        stockVO.getUpDownPercent(),stockVO.getBoardName());
            }
        }else{
            queryForm.getSma().setLatelyDay(queryForm.getLatelyDay());
            for(PickStockVO stockVO : pickList){
                List<StockKlineDailyModel> dailyList = stockKlineDailyService.getStockKlineDailyList(
                        stockVO.getStockCode(),queryForm.getStartDate(),queryForm.getEndDate());
                if(CollUtil.isEmpty(dailyList)){
                    continue;
                }
                boolean result = StockAnalyzer.detectSMA(dailyList,queryForm.getSma());
                if(!result){
                   continue;
                }
                log.info("## 符合条件的股票：{}--{},最新价：{},涨跌幅：{}%, 所属行业板块：{}",
                        stockVO.getStockName(), stockVO.getStockCode(),stockVO.getPrice(),
                        stockVO.getUpDownPercent(),stockVO.getBoardName());
                fundList.add(FundTopBoardStockModel.transModel(stockVO));
            }
        }
        fundList = fundList.stream().sorted(Comparator.comparing(FundTopBoardStockModel::getMainSumAmt).reversed()).collect(Collectors.toList());
        //持久化
        if(queryForm.getHasPersistent() == 1 && CollUtil.isNotEmpty(fundList)){
            fundTopBoardStock.saveBatch(fundList);
        }

        String contentText = String.format("选股条件：流通总市值 %f (元) 到 %f(元), 换手率>=%f," +
                        "近%d天主力净流入大于:%f万，%s MA5,MA10,MA20均线多头向上",
                queryForm.getMinTradeMv(),queryForm.getMaxTradeMv(),queryForm.getExchangeRate(),queryForm.getLatelyDay(),1000f,DateUtil.now());
        MailInfoForm form = MailInfoForm.me(mailConfig,"自动选股策略-"+ DateUtil.now(),contentText);
        MailUtil.transHtml(form,fundList,queryForm.getLatelyDay());
        MailUtil.senderAsync(form);
        return null;
    }
}
